package org.kk.str;

/**
 * 替换空格
 * @author kk
 * @Date 2021/1/21
 */
public class ReplaceBlank {
    /**
     * 解法一 从后往前复制
     */
    public static String replaceBlank(String s){
        if(s == null || s.length() == 0) return new String();
        int blankNum = 0;
        int length = s.length();
        int newLength = 0;
        for (int i = 0; i < length; i++) {
            if(s.charAt(i) == ' '){
                blankNum++;
            }
        }
        newLength = length + 2 * blankNum;
        char[] newChars = new char[newLength];
        int index = newLength -1;
        for (int i = length -1; i >= 0; i--) {
            if(s.charAt(i) == ' '){
                newChars[index--] = '0';
                newChars[index--] = '2';
                newChars[index--] = '%';
            }else{
                newChars[index--] = s.charAt(i);
            }
        }
        return new String(newChars);
    }
}
